package org.example.test;

import java.util.concurrent.atomic.AtomicReference;

// 定义一个共享的数据类
class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // getter和setter
    public String getName() { return name; }
    public int getAge() { return age; }
    public void setName(String name) { this.name = name; }
    public void setAge(int age) { this.age = age; }

    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + "}";
    }
}

public class AtomicReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        // 初始化AtomicReference，持有一个User对象
        final Integer[] sum = {0};
        AtomicReference<Integer> sum1 = new AtomicReference<>();

        // 线程1：尝试更新用户年龄
        Thread thread1 = new Thread(() -> {
            sum[0] = sum[0] +1;
            sum1.set(1);
            System.out.println("线程1更新结果：" + sum[0]);
        });

        // 线程2：同时尝试更新用户姓名
        Thread thread2 = new Thread(() -> {
            sum[0] = sum[0] +2;
            sum1.set(2);
            System.out.println("线程2更新结果：" + sum[0]);
        });
        // 线程2：同时尝试更新用户姓名
        Thread thread3 = new Thread(() -> {
            sum[0] = sum[0] +3;
            sum1.set(3);
            System.out.println("线程3更新结果：" + sum[0]);
        });

        // 启动线程
        thread1.start();
        thread2.start();
        thread3.start();
        thread1.join();
        thread2.join();
        thread3.join();

        // 最终结果（两个线程中只有一个能成功更新）
        System.out.println("最终用户信息：" + sum[0]);
        System.out.println("最终用户信息：" + sum1.get());
    }
}
